package net.nagaseyasuhito.nicola.entity;

import java.util.HashSet;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.OrderBy;
import javax.persistence.Table;

import org.apache.commons.codec.digest.DigestUtils;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.Sort;
import org.hibernate.annotations.SortType;

@Entity
@org.hibernate.annotations.Entity(dynamicInsert = true, dynamicUpdate = true)
@Table(name = "User_")
public class User extends BaseEntity {
	private static final long serialVersionUID = 1L;

	@Column(nullable = false, unique = true)
	@Lob
	private String name;

	@Column(nullable = false)
	@Lob
	private String password;

	@OneToOne(optional = false, fetch = FetchType.LAZY)
	@Cascade({CascadeType.ALL, CascadeType.DELETE_ORPHAN})
	private Image image;

	@OneToMany
	private Set<User> friends;

	@OneToMany
	@JoinColumn(name = "user__id")
	@Cascade({CascadeType.ALL, CascadeType.DELETE_ORPHAN})
	@Sort(type = SortType.NATURAL)
	@OrderBy("createTimestamp desc")
	private SortedSet<Entry> entries;

	public User addFriend(User friend) {
		if(this.getFriends() == null) {
			this.setFriends(new HashSet<User>());
		}
		this.getFriends().add(friend);
		
		return this;
	}

	public User addEntry(Entry entry) {
		if(this.getEntries() == null) {
			this.setEntries(new TreeSet<Entry>());
		}
		this.getEntries().add(entry);
		entry.setUser(this);

		return this;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = DigestUtils.md5Hex(password);
	}

	public Image getImage() {
		return image;
	}

	public void setImage(Image image) {
		this.image = image;
	}

	public Set<User> getFriends() {
		return friends;
	}

	public void setFriends(Set<User> friends) {
		this.friends = friends;
	}

	public SortedSet<Entry> getEntries() {
		return entries;
	}

	public void setEntries(SortedSet<Entry> entries) {
		this.entries = entries;
	}
}
